设计模式:如何优雅地手写生产者消费者模式 您所在的位置:网站首页 生产者消费者 设计模式 设计模式:如何优雅地手写生产者消费者模式

设计模式:如何优雅地手写生产者消费者模式

2024-05-19 03:07| 来源: 网络整理| 查看: 265

生产者消费者模式并不是GOF提出的23种设计模式之一,23种设计模式都是建立在面向对象的基础之上的,但其实面向过程的编程中也有很多高效的编程模式,生产者消费者模式便是其中之一,它是我们编程过程中最常用的一种设计模式。

在应用解耦、流量削峰等场景下常需要用到消息队列,生产者不断生产消息投递到队列里面,不必等待消费者消费;消费者从队列里面取消息进行处理,不需要找生产者要数据;这就是典型的生产者消费者模式,平衡了生产者消费者的处理能力,达到了解耦的目的。

当面试中被问“你了解那些设计模式”的时候,只回答一个单例模式未免显得有点不够专业,多了解一下效果可能会稍好一点。和单例模式对比,生产者消费者模式实现也比较简单,适合手写;对于其中的细节又可以再挖掘。

不多叨叨了,本文就自己实现一个阻塞队列,然后创建生产者和消费者,来实现一个简单的生产者消费者模式。

实现阻塞队列 生产者在队列未满时一直生产,满了则停止生产; 消费者在队列不为空的时候一直消费,空了则停止消费; 当消费者发现队列里面没有消息了通知生产者生产; 当生产者生产了消息通知消费者消费。 public class MyBlockingQueue { private int maxSize; private List queue; public MyBlockingQueue(int maxSize) { this.maxSize = maxSize; this.queue = new ArrayList(); } public synchronized void put() { while (queue.size() == maxSize) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Long value = System.currentTimeMillis(); queue.add(value); System.out.println("put:" + value); notify(); } public synchronized void take() { while (queue.isEmpty()) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Long value = queue.get(0); System.out.println("take:" + value); queue.remove(0); notify(); } } 实现生产者 public class Producer implements Runnable { private MyBlockingQueue queue; public Producer(MyBlockingQueue queue) { this.queue = queue; } @Override public void run() { while (true) { queue.put(); } } } 实现消费者 public class Consumer implements Runnable { private MyBlockingQueue queue; public Consumer(MyBlockingQueue queue) { this.queue = queue; } @Override public void run() { while (true) { queue.take(); } } } 实现生产者消费者模型 public class Main { public static void main(String[] args) throws InterruptedException { MyBlockingQueue queue = new MyBlockingQueue(100); Producer producer = new Producer(queue); Consumer consumer = new Consumer(queue); new Thread(producer).start(); Thread.sleep(10); new Thread(consumer).start(); } }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有